package emergency;

import java.util.ArrayList;

import unit.*;

public class RequirementsRobbery extends RequirementsEmergency {

	/**
	 * Checks if this requirement is the right one to handle the given emergency
	 * 
	 * @param emergency
	 *            the emergency to check if this Requirement needs to handle it
	 * 
	 * @return Returns true if this is the right requirement for the given
	 *         emergency, false if not
	 */
	@Override
	boolean canHandleEmergency(Emergency emergency) {
		return (emergency instanceof Robbery);
	}

	/**
	 * Method that will handle the requirements of the given emergency if the
	 * emergency is none of the previous members of the chain that can handle it
	 * 
	 * @param emergency
	 *            the given emergency of which the requirements will be
	 *            processed
	 * @param units
	 *            list of units that out of which the needed units will be
	 *            picked
	 * 
	 * @return a list of suggested units to assign to the emergency
	 * 
	 * @throws IllegalArgumentException
	 *             , if not enough units are in the given list to handle the
	 *             emergency
	 */
	@Override
	ArrayList<Unit> createSuggestion(Emergency emergency, ArrayList<Unit> units) {
		if (canHandleEmergency(emergency)) {
			ArrayList<Unit> suggestedUnits = new ArrayList<Unit>();
			setRequirements(emergency);

			int pol = getTotalPoliceCarsNeeded();

			for (Unit u : units) {
				if (u instanceof PoliceCar) {
					if (pol > 0) {
						suggestedUnits.add(u);
						pol--;
					}
				}
			}
			emergency.setEmergencyRequirements(this);

			if (pol == 0)
				return suggestedUnits;
			else
				throw new IllegalArgumentException(
						"Not enough units given to handle this emergency");
		} else {
			return getNextInChain().createSuggestion(emergency, units);
		}
	}

	/**
	 * Method for setting the total units needed, depending on this requirement
	 * 
	 * @post The total amount of ambulances needed is set, depending on this
	 *       requirement
	 * 
	 * @post The total amount of policecars needed is set, depending on this
	 *       requirement
	 * 
	 * @post The total amount of firetrucks needed is set, depending on this
	 *       requirement
	 * 
	 * @post The total amount of units needed is set, depending on this
	 *       requirement
	 */
	@Override
	void setRequirements(Emergency emergency) {
		if (canHandleEmergency(emergency)) {
			emergency.setEmergencyRequirements(this);
			Robbery robbery = (Robbery) emergency;

			if (robbery.isInProgress() && robbery.isArmed())
				setTotalPoliceCarsNeeded(3);
			else
				setTotalPoliceCarsNeeded(1);

			// check already assigned unit (if only 1 unit is broke).
			int alreadyAssigned = amountOfAssignedUnits("PoliceCar",
					emergency.getUnitsClone());

			setTotalPoliceCarsNeeded(diff(getTotalPoliceCarsNeeded(),
					alreadyAssigned));
			setTotalUnitsNeeded(getTotalPoliceCarsNeeded());
		} else
			getNextInChain().setRequirements(emergency);

	}
}
